package com.sumer.psychology.microblog.application.query;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.sumer.psychology.common.persistence.mongodb.AbstractMongoRepository;

/**
 * 微博查询
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/10/28
 * Time: 15:02
 */
public class MicroBlogQueryApplicationService extends AbstractMongoRepository {
    private static final String DB_NAME = "sumer_micro_blog";

    /**
     * 列出所有的微博
     *
     * @param countPerPage count per page
     * @param offset       off set
     * @return json
     */
    public String list(int countPerPage, int offset) {
        DBCursor results = db().getCollection(dbName())
                .find()
                .skip(offset)
                .limit(countPerPage)
                .sort(new BasicDBObject("createTime", -1));

        return serializeWithTotalCount(null, results);
    }

    /**
     * 查找一个作者的所有微博
     *
     * @param authorId     author id
     * @param countPerPage count per page
     * @param offset       off set
     * @return json
     */
    public String findByAuthor(String authorId, int countPerPage, int offset) {
        DBObject queryCondition = new BasicDBObject("author.identity", authorId);

        DBCursor results = db().getCollection(dbName())
                .find(queryCondition)
                .skip(offset)
                .limit(countPerPage)
                .sort(new BasicDBObject("createTime", -1));

        return serializeWithTotalCount(queryCondition, results);
    }

    /**
     * 查找唯一的微博
     *
     * @param microBlogId id
     * @return json
     */
    public String findOneMicroBlog(String microBlogId) {
        DBObject result = findOne(microBlogId);
        return serialize(result);
    }

    @Override
    protected String dbName() {
        return DB_NAME;
    }

}
